package util

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
	"regexp"
	"time"

	"mindonmap/pkgs/setting"
)

// 存 s3
func WriteFile_s3(acid string, Mindid string, base64_image_content string) string {
	b, err := regexp.MatchString(`^data:\s*image\/(\w+);base64,`, base64_image_content)
	if !b {
		return ""
	}
	re, _ := regexp.Compile(`^data:\s*image\/(\w+);base64,`)
	allData := re.FindAllSubmatch([]byte(base64_image_content), 2)

	fileType := string(allData[0][1]) //png ，jpeg 后缀获取
	base64Str := re.ReplaceAllString(base64_image_content, "")

	now := time.Now()
	filepath := now.Format("2006-01-02")
	var Filename = filepath + "/" + acid + "preview/" + Mindid + "." + fileType

	buffer, _ := base64.StdEncoding.DecodeString(base64Str)
	buffers := bytes.NewBuffer(buffer)

	var size int64 = int64(buffers.Len())
	fmt.Println(size)
	//fmt.Println(buffers)
	//buffers.Read(buffer)
	//bufferes := make([]byte, size)

	var aws3 = setting.GetAWSS3()
	AccessKeyID := aws3.AccessKeyID
	SecretAccessKey := aws3.SecretAccessKey
	S3Region := aws3.S3Region
	S3Bucket := aws3.S3Bucket

	creds := credentials.NewStaticCredentials(AccessKeyID, SecretAccessKey, "")
	s, err := session.NewSession(&aws.Config{
		Region:      aws.String(S3Region),
		Credentials: creds,
	})
	if err != nil {
		fmt.Println(err)
	}

	_, err = s3.New(s).PutObject(&s3.PutObjectInput{
		Bucket:             aws.String(S3Bucket),
		Key:                aws.String(Filename),
		ACL:                aws.String("public-read"),
		Body:               bytes.NewReader(buffer),
		ContentLength:      aws.Int64(size),
		ContentType:        aws.String("image/jpeg"),
		ContentDisposition: aws.String("attachment"),
	})
	if err != nil {
		fmt.Println(err)
	}

	imageurl := "/" + Filename
	return imageurl
}
